package com.sanglh.tutorial.common.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class MultiChoiceImageButtonGroup extends LinearLayout {
	private OnClickListener mChildOnClickListener;
	private OnSelectedChangeListener mOnSelectedChangeListener;
	private PassThroughHierarchyChangeListener mPassThroughListener;

	public MultiChoiceImageButtonGroup(Context context) {
		super(context);
		init();
	}

	public MultiChoiceImageButtonGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		mChildOnClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mOnSelectedChangeListener != null) {
					mOnSelectedChangeListener.onSelectedChanged(v.getId());
				}
				setSelectedView(v);
			}

		};
		mPassThroughListener = new PassThroughHierarchyChangeListener();
		super.setOnHierarchyChangeListener(mPassThroughListener);
	}

	private void setSelectedView(View v) {
		boolean isSelected = v.isSelected();
		v.setSelected(!isSelected);

	}

	public void setSelectedView(int id) {
		View  v = findViewById(id);
		boolean isSelected = v.isSelected();
		v.setSelected(!isSelected);

	}

	@Override
	public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
		mPassThroughListener.mOnHierarchyChangeListener = listener;
	}

	private class PassThroughHierarchyChangeListener implements
			ViewGroup.OnHierarchyChangeListener {
		private ViewGroup.OnHierarchyChangeListener mOnHierarchyChangeListener;

		public void onChildViewAdded(View parent, View child) {
			if (parent == MultiChoiceImageButtonGroup.this && child instanceof ImageButton) {
				((ImageButton) child).setOnClickListener(mChildOnClickListener);
			}

			if (mOnHierarchyChangeListener != null) {
				mOnHierarchyChangeListener.onChildViewAdded(parent, child);
			}
		}

		public void onChildViewRemoved(View parent, View child) {
			if (parent == MultiChoiceImageButtonGroup.this && child instanceof ImageButton) {
				((ImageButton) child).setOnClickListener(null);
			}

			if (mOnHierarchyChangeListener != null) {
				mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
			}
		}
	}

	public int getSelectedView() {
		int count = getChildCount();
		for (int i = 0; i < count; i++) {
			View view = getChildAt(i);
			if (view.isSelected()) {
				return i;
			}
		}
		return -1;
	}

	public void setOnSelectedChangeListener(
			OnSelectedChangeListener selectedChangeListener) {
		this.mOnSelectedChangeListener = selectedChangeListener;
	}

	public interface OnSelectedChangeListener {
		void onSelectedChanged(int id);
	}

}
